<?php

namespace App\Imports;

use App\Http\Models\Business\Payer;
use App\Http\Models\Business\RetailContractIndicator;
use App\Http\Models\CategoryContract;
use Exception;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class RetailContractIndicatorImport implements ToCollection, WithHeadingRow
{
    use BaseImportTrait;

    private $required_field = ['年份', '客户代码', '品类代码', '指标'];

    private $payer_id_array = [];
    private $category_contract_id_array = [];

    public function collection(Collection $rows)
    {
        foreach ($rows as $key => $row) {
            $row = $row->toArray();

            if ($key === 0) {
                $this->verifyField($row);
                $this->prepareBaseData();
            }

            $this->verifyValue($row, $key + 2);

            $this->saveData($row);
        }
    }


    //准备基础数据，用来验证
    private function prepareBaseData()
    {
        $this->payer_id_array = Payer::pluck('code')->toArray();
        $this->category_contract_id_array = CategoryContract::pluck('id')->toArray();
    }


    //验证字段值是否合理，比如不为空，比如在数据库中是否存在
    private function verifyValue(array $row, int $index)
    {
        //首先每个字段都要有值，不能存在空值。
        $no_error = true;
        $error_field = '';

        foreach ($this->required_field as $field) {
            if ($row[$field] == '') {
                $no_error = false;
                $error_field = $field;
                break;
            }
        }
        if (!$no_error) {
            throw new Exception('第 ' . $index . ' 行中的 [' . $error_field . '] 列项缺少内容值');
        }

        //判断数据库中存在基础值
        if (!in_array($row['客户代码'], $this->payer_id_array)) {
            $no_error = false;
            $error_field = '客户代码';
        } elseif (!in_array($row['品类代码'], $this->category_contract_id_array)) {
            $no_error = false;
            $error_field = '品类代码';
        }

        if (!$no_error) {
            throw new Exception('第 ' . $index . ' 行中的 [' . $error_field . '] 的值不存在于系统中！');
        }
    }


    //保存数据
    private function saveData(array $row)
    {
        $model = new RetailContractIndicator();
        $model->year = $row['年份'];
        $model->payer_code = $row['客户代码'];
        $model->category_contract_id = $row['品类代码'];
        $model->amount = $row['指标'];
        $model->save();
    }
}
